import {
		getLoginInfo
	} from '@/xiaoyun/api/user.js'
	import {
		loginFn
	} from '@/xiaoyun/login.js'
const state = {
	openid: null,
	access_token: null,
	session_key: null,
	userInfo: {},
	isLogin: false
}

const mutations = {
	SET_USER_INFO(state, userInfo) {
		state.userInfo = userInfo
	},
	SET_USER_NICKNAME(state, nickname) {
		state.userInfo.nickname = nickname
		let userInfo = uni.getStorageSync('chamberlain_user_info')
		userInfo.nickname = nickname
		uni.setStorageSync('chamberlain_user_info',userInfo)
	},
	SET_USER_AVATAR(state, avatar) {
		state.userInfo.avatar = avatar
		let userInfo = uni.getStorageSync('chamberlain_user_info')
		userInfo.avatar = avatar
		uni.setStorageSync('chamberlain_user_info',userInfo)
	},
	SET_LOGIN_STATUS(state, status) {
		state.isLogin = status
	},
	SET_OPENID(state, openid) {
		state.openid = openid
	}
}

const actions = {
	login(context) {
		uni.showLoading({
			title: '登录中'
		})
		console.log('来啦捏');
		loginFn().then(co => {
			getLoginInfo({
				code: co
			}).then(res => {
				if (res.code === 200) {
					// 用户信息
					context.commit('SET_USER_INFO', res.data)
					context.commit('SET_OPENID', res.data.openid)
					uni.setStorageSync('chamberlain_user_info', res.data)
					console.log('首次进入登录this.userInfo', context);
					// 登录状态
					context.commit('SET_LOGIN_STATUS', true)
					uni.setStorageSync('chamberlain_login_status', true)
				}
				uni.showToast({
					title: '登录成功',
					icon: res.code === 200 ? 'success' : 'error',
					duration: 1500
				});
			}).catch(err => {
				console.log('登录失败？',err);
				uni.showToast({
					title: err.msg,
					icon: 'fail',
					duration: 1500
				});
			})
		}).catch(err => {
			uni.showToast({
				title: '获取登录信息失败，请重新打开小程序或者使用其他登录方式',
				icon: 'fail',
				duration: 1500
			});
		}).finally(()=>{
			uni.hideLoading()
		})
	}
}

const getters = {
	userInfo: state => state.userInfo,
	accessToken: state => state.userInfo.access_token,
	avatar: state => state.userInfo.avatar,
	gendesr: state => state.userInfo.gendesr,
	nikename: state => state.userInfo.nikename,
	openid: state => state.userInfo.openid,
	phone: state => state.userInfo.phone,
	sessionKey: state => state.userInfo.session_key,
	unionid: state => state.userInfo.unionid
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
}